package edu.ccut.saturn.workflow.rollbackModule.code;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import edu.ccut.saturn.component.SaturnData;
import edu.ccut.saturn.operation.Operation;
import edu.ccut.saturn.workflow.common.Constants;

public class RollbackUtil {
	static List<Object> getActInstIdList(Object actInstId, Connection conn)
			throws Exception {
		List<Object> result = new ArrayList<Object>();
		// 查询下一活动实例ID集合
		ArrayList<SaturnData> actInstIdlist = Operation.dataBase()
				.queryByCondition(Constants.SATURNDATA_WF_TRANSITION,
						" and CAUSEACTINST_ID = '" + actInstId + "'", conn);
		// 循环判断需要返回的
		for (SaturnData trans : actInstIdlist) {
			Object id = trans.get("resultactinst_id");
			SaturnData saturnData = Operation.dataBase().queryByPrimaryKey(
					Constants.SATURNDATA_WF_ACTIVITY_INSTANCE, id + "", conn);
			String type = saturnData.get("type") + "";
			if (Constants.ACTIVITY_TYPE_DECISION.equals(type)) {
				result.addAll(getActInstIdList(id, conn));
			} else if (Constants.ACTIVITY_TYPE_MAN.equals(type)) {
				result.add(id);
			}
		}
		return result;
	}
	/**
	 * 得到要插入的回滚路经数据项
	 * @return
	 * @throws Exception 
	 */
	static List<SaturnData> getTransMapList(Object actInstId, Connection conn) throws Exception{
		List<SaturnData> result = new ArrayList<SaturnData>();
		// 查询下一活动实例ID集合
		ArrayList<SaturnData> actInstIdlist = Operation.dataBase()
				.queryByCondition(Constants.SATURNDATA_WF_TRANSITION,
						" and CAUSEACTINST_ID = '" + actInstId + "'", conn);
		String transtime = Operation.baseService().GetSystemTime();
		// 循环判断
		for (SaturnData trans : actInstIdlist) {
			Object resultActInstId = trans.get("resultactinst_id");
			SaturnData saturnData = Operation.dataBase().queryByPrimaryKey(
					Constants.SATURNDATA_WF_ACTIVITY_INSTANCE, resultActInstId + "", conn);
            //重新装配trans数据项
			Object temp = null;
			temp = trans.get("causeactinst_id");
			trans.set("causeactinst_id", trans.get("resultactinst_id"));
			trans.set("resultactinst_id", temp);
			
			temp = trans.get("causeactinst_name");
			trans.set("causeactinst_name", trans.get("resultactinst_name"));
			trans.set("resultactinst_name", temp);
			
			temp = trans.get("srcactdef_id");
			trans.set("srcactdef_id", trans.get("destactdef_id"));
			trans.set("destactdef_id", temp);
			
			temp = trans.get("srcactdef_name");
			trans.set("srcactdef_name", trans.get("destactdef_name"));
			trans.set("destactdef_name", temp);
			
			trans.set("transtime", transtime);
			
			trans.set("transition_id", null);
			result.add(trans);
			String type = saturnData.get("type") + "";
			if (Constants.ACTIVITY_TYPE_DECISION.equals(type)) {
				result.addAll(getTransMapList(resultActInstId, conn));
			} 
		}
		return result;
	}

}
